/*
 * @Author: 张久冬
 * @Date: 2021-12-27 16:45:03
 * @
# Description:
 */
export let firstMenu: any = null
import { IBreadcrumb } from '@/base-ui/breadcrumb'
import type { RouteRecordRaw } from 'vue-router'
// 根据用户数据创建路由地址
export function mapMenusToRouters(userMenus: any[]): RouteRecordRaw[] {
  const routers: RouteRecordRaw[] = []
  // 1.默认加载所有的对应路由
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  // console.log(allRoutes)

  // 2.递归对应菜单添加路由地址
  const _recurseGetRoute = (menus: any[]) => {
    menus.map((menu) => {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) {
          routers.push(route)
        }
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    })
  }
  _recurseGetRoute(userMenus)
  return routers
}
// 根据当前地址获取导航菜单的选中项
export function pathMaptoMenu(
  userMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMaptoMenu(menu.children, currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) return menu
  }
}
// 根据当前地址获取面包屑地址
export function pathMapBreadcrumbs(
  userMenus: any[],
  currentPath: string
): IBreadcrumb[] {
  const breadcrumbs: IBreadcrumb[] = []
  pathMaptoMenu(userMenus, currentPath, breadcrumbs)

  return breadcrumbs
}
// // 根据当前地址获取导航菜单的选中项
// export function pathMaptoMenu(userMenus: any[], currentPath: string): any {
//   for (const menu of userMenus) {
//     if (menu.type === 1) {
//       const findMenu = pathMaptoMenu(menu.children, currentPath)
//       if (findMenu) return findMenu
//     } else if (menu.type === 2 && menu.url === currentPath) return menu
//   }
// }
// export function pathMapBreadcrumbs(
//   userMenus: any[],
//   currentPath: string
// ): IBreadcrumb[] {
//   const breadcrumbs: IBreadcrumb[] = []
//   for (const menu of userMenus) {
//     if (menu.type === 1) {
//       const findMenu = pathMaptoMenu(menu.children, currentPath)
//       if (findMenu) {
//         breadcrumbs.push({ name: menu.name })
//         breadcrumbs.push({ name: findMenu.name })

//         return findMenu
//       }
//     } else if (menu.type === 2 && menu.url === currentPath) return menu
//   }
//   return breadcrumbs
// }
